package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");

        //创建一个线程池  要可以一直扩容的那种
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();
         /* Thread t = new Thread(() -> {
              try {
                  processConnection(clientSocket);
              }catch (IOException e) {
                  e.printStackTrace();
              }
          });
          t.start();*/
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    //通过这个方法来处理一个连接
    private void processConnection(Socket clientSocket) throws IOException {
        //1.打印一个日志,告知客户端连上了
        System.out.printf("[%s:%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        //2.从socket中获取到流对象,来进一步的进行后续操作
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //3.搞一个循环  针对每个连接  客户端可能会有多个请求,服务器就有多个响应了
            Scanner scanner = new Scanner(inputStream);
            while (true) {
                //读取请求并解析
                if (!scanner.hasNext()) {
                    //如果发现后续没有数据了,说明此时的TCP的连接已经断开了
                    System.out.printf("[%s:%d]客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request  = scanner.next();
                //3.2 根据请求计算响应
                String response = process(request);

               // 把响应写回客户端
               //outputStream.write(response.getBytes(),0,response.getBytes().length);
               // outputStream.flush();
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                // 强制刷新缓冲区
                writer.flush();
                //服务器打印日志
                System.out.printf("[%s:%d] req = %s,resp = %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            //再这里关闭资源比较靠谱
            clientSocket.close();
        }
    }

    //回显服务器
   public String process(String request) {
        //在这里加一个换行符  告诉客户端也有明显的分隔符
        return request + "\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
